package naga.x.platform2.app;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AppErrorController implements ErrorController {
	
	public static final String PATH = "/error";

	protected HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		try {
			return HttpStatus.valueOf(statusCode);
		} catch (Exception ex) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
	}
	
	@RequestMapping(path = PATH, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public String error(HttpServletRequest req, String msg) {
		return "{\"msg\": \"" + (msg != null ? msg : getStatus(req).getReasonPhrase()) + "\"}";
	}

	@Override
	public String getErrorPath() {
		return PATH;
	}

}
